/****
	Copyright 2012 Taras Kulbachka

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package com.atdevsoft.apps.abyss;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.database.Cursor;
import android.net.Uri;
import android.text.Html;

public class ExportManager {
	private static final String QUOTES_SEPARATOR = "===============================";
    
	// returns uri of the file created
	public Uri exportToAutonamedFile(String query) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
		File sdDir = DatabaseHelper.getDefaultWorkingDir();
		File exportFile = new File(sdDir, "export" + sdf.format(new Date()) + ".txt");
			
		if (!exportFile.exists()) {
			try {
				exportFile.createNewFile();
			} catch (IOException e) {
				return null;
			}
		}
		  
		if (exportToFile(exportFile, query)) {
			return Uri.fromFile(exportFile);
		}
		return null;
	}
	
	public boolean exportToFile(File fl, String query) {
		Cursor data = DatabaseHelper.rawQuery(query, null);
		if (data.getCount() <= 0) {
			data.close();
			return false;
		}
		data.moveToFirst();
		try {
			BufferedWriter buff = new BufferedWriter(new FileWriter(fl, true));
			
			while (!data.isAfterLast()) {
				if (!data.isFirst()) {
					buff.append(QUOTES_SEPARATOR);
					buff.newLine();
				}
				for (int i = 0; i < data.getColumnCount(); i++) {
					buff.append(Html.fromHtml(data.getString(i)).toString().trim());
					buff.newLine();
				}				
				data.moveToNext();
			}	
			buff.close();
		} catch (IOException e) {
			data.close();
			return false;
		}
		
		data.close();
		return true;
	}
	
}
